var path = require("path");
var dao = require(path.join(process.cwd(), "dao/DAO"));
var formatData = require("./formatData.js");
var upload_config = require('config').get("upload_config");

/**
 *  添加收藏
 * 
 *  @param {[type]}   params 收藏数据 
 *  @param {Function} cb  回调函数
 */
module.exports.createCollection = function (params, cb) {
    dao.create("CollectionModel", params, function (err, collection) {
        if (err) return cb({
            msg: "添加收藏：添加失败！",
            code: err.name == "SequelizeValidationError" ? 400 : 500,
            stack: err
        });
        cb(null, {
            msg: "添加收藏：添加成功！",
            code: 201,
            data: formatData(collection)
        });
    });
}

/**
 *  删除收藏
 * 
 *  @param  {[type]}   id     收藏ID
 *  @param  {Function} cb     回调函数
 */
module.exports.deleteCollection = function (id, cb) {
    if (!id) return cb({
        msg: "删除收藏：ID不能为空！",
        code: 400,
        stack: null
    });
    if (!Array.isArray(id)) id = [id];
    if (id.every(item => isNaN(parseInt(item)))) return cb({
        msg: "删除收藏：ID必须是数字！",
        code: 400,
        stack: null
    });
    dao.destroyMany("CollectionModel", id, function (err) {
        if (err) return cb({
            msg: "删除收藏：删除失败！",
            code: 500,
            stack: err
        });
        cb(null, {
            msg: "删除收藏：删除成功！",
            code: 200,
            data: null
        });
    });
}

/**
 *  更新收藏
 * 
 *  @param  {[type]}   id   收藏ID
 *  @param  {[type]}   data 新数据
 *  @param  {Function} cb   回调函数
 */
module.exports.updateCollection = function (id, data, cb) {
    if (!id || isNaN(parseInt(id))) return cb({
        msg: "更新收藏：ID不合法！",
        code: 400,
        stack: null
    });
    dao.update("CollectionModel", id, data, function (err, collection) {
        if (err) return cb({
            msg: "更新收藏：更新失败！",
            code: err.name == "SequelizeValidationError" ? 400 : 500,
            stack: err
        });
        cb(null, {
            msg: "更新收藏：更新成功！",
            code: 200,
            data: formatData(collection)
        });
    });
}

/**
 *  修改收藏删除状态
 * 
 *  @param  {[type]}   id      收藏ID
 *  @param  {[type]}   deleted 0未删除 1已删除
 *  @param  {Function} cb      回调函数
 */
module.exports.updateCollectionDeleted = function (id, deleted, cb) {
    if (!id || isNaN(parseInt(id))) return cb({
        msg: "更新收藏删除状态：ID不合法！",
        code: 400,
        stack: null
    });
    dao.update("CollectionModel", id, { "deleted": deleted }, function (err, collection) {
        if (err) return cb({
            msg: "更新收藏删除状态：设置状态失败！",
            code: err.name == "SequelizeValidationError" ? 400 : 500,
            stack: err
        });
        cb(null, {
            msg: "更新收藏删除状态：设置状态成功！",
            code: 200,
            data: formatData(collection)
        });
    });
}

/**
 *  根据条件获取收藏列表
 *  @param  {[type]}   conditions 查询条件
 *  conditions{
        "where" : 条件查询,
        "order" : 排序
        "pagenum" : 页数,
        "pagesize" : 每页长度
    }
 *  @param  {Function} cb         回调函数
 */
module.exports.getAllCollections = function (conditions, cb) {
    if (!conditions.pagenum || conditions.pagenum <= 0) return cb({
        msg: "获取收藏列表：pagenum 参数不合法！",
        code: 400,
        stack: null
    });
    if (!conditions.pagesize || conditions.pagesize <= 0) return cb({
        msg: "获取收藏列表：pagesize 参数不合法！",
        code: 400,
        stack: null
    });
    dao.countByConditions("CollectionModel", conditions, function (err, count) {
        if (err) return cb({
            msg: "获取收藏列表：获取总数失败！",
            code: 500,
            stack: err
        });
        pagenum = parseInt(conditions["pagenum"]);
        pagesize = parseInt(conditions["pagesize"]);
        pageCount = Math.ceil(count / pagesize);
        offset = (pagenum - 1) * pagesize;
        if (offset >= count) {
            offset = count;
        }
        limit = pagesize;
        conditions["offset"] = offset;
        conditions["limit"] = limit;
        conditions["order"] = conditions["order"] || "-add_time";
        conditions["attributes"] = {
            include: [
                [
                    global.database.sequelize.literal(`(
                        SELECT group_concat(good_pic.mid)
                        FROM good_pic
                        WHERE good_pic.good_id = CollectionModel.good_id
                    )`),
                    'good_pic'
                ],
            ]
        }
        conditions["include"] = [{
            association: global.database.association["collection_good"],
            attributes: ["name","price","is_promote","promote_price"]
        }];
        dao.list("CollectionModel", conditions, function (err, collection) {
            if (err) return cb({
                msg: "获取收藏列表：获取分页数据失败！",
                code: 500,
                stack: err
            });
            var resultDta = {};
            for (idx in collection) {
                var pics = collection[idx].dataValues.good_pic;
                pics = pics ? pics.split(",") : [];
                pics = pics.map(function (pic) {
                    return pic.indexOf("http") == 0 ? pic : upload_config.get("baseURL") + pic;
                });
                collection[idx].good_pic = pics;
            }
            resultDta["total"] = count;
            resultDta["pagenum"] = pagenum;
            resultDta["collection"] = collection.map(formatData);
            cb(null, {
                msg: "获取收藏列表：获取分页数据成功！",
                code: 200,
                data: resultDta
            });
        });
    });
}

/**
 *  根据id获取收藏对象
 * 
 *  @param  {[type]}   id 收藏ID
 *  @param  {Function} cb 回调函数
 */
module.exports.getCollectionById = function (id, cb) {
    if (!id || isNaN(parseInt(id))) return cb({
        msg: "获取收藏对象：ID不合法！",
        code: 400,
        stack: null
    });
    dao.findByID("CollectionModel", id, function (err, collection) {
        if (err) return cb({
            msg: "获取收藏对象：获取失败！",
            code: 500,
            stack: err
        });
        if (!collection) return cb({
            msg: "获取收藏对象：对象不存在！",
            code: 403,
            stack: null
        });
        cb(null, {
            msg: "获取收藏对象：获取成功！",
            code: 200,
            data: formatData(collection)
        });
    });
}